package com.mdd.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.order.Mansion;
import com.mdd.common.mapper.order.AddressMapper;
import com.mdd.common.mapper.order.MansionMapper;
import com.mdd.common.util.LocationUtils;
import com.mdd.front.service.IMansionService;
import com.mdd.front.validate.commons.PageValidate;
import com.mdd.front.validate.order.MansionSearchValidate;
import com.mdd.front.vo.order.AddressVo;
import com.mdd.front.vo.order.MansionVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 大厦服务类
 * @author shenjian
 * @createTime 2023年02月06日 22:43:00
 */
@Service
public class MansionServiceImpl implements IMansionService {

    @Resource
    MansionMapper mansionMapper;

    @Override
    public List<MansionVo> list(MansionSearchValidate searchValidate) {

        QueryWrapper<Mansion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("id");
        queryWrapper.select(Mansion.class, info ->
                !"is_delete".equals(info.getColumn()) &&
                !"delete_time".equals(info.getColumn()) &&
                !"update_time".equals(info.getColumn()));

        mansionMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "=:sn:str",
                "like:name:str"
        });
        List<Mansion> mansionList = this.mansionMapper.selectList(queryWrapper);

        List<MansionVo> list = new LinkedList<>();
        for(Mansion mansion : mansionList) {
            MansionVo vo = new MansionVo();
            BeanUtils.copyProperties(mansion, vo);
            // 计算位置
            if (searchValidate.getLatitude() != null && searchValidate.getLongitude() != null &&
                    mansion.getLatitude() != null && mansion.getLongitude() != null) {
                vo.setDistance(Math.round(LocationUtils.getDistance(searchValidate.getLatitude(), searchValidate.getLongitude(),
                        mansion.getLatitude(), mansion.getLongitude()).intValue()));
            }
            list.add(vo);
        }

        return list.stream().sorted(Comparator.comparing(MansionVo::getDistance)).collect(Collectors.toList());
    }

    @Override
    public MansionVo detail(Integer id) {
        final Mansion mansion = this.mansionMapper.selectById(id);
        MansionVo vo = new MansionVo();
        BeanUtils.copyProperties(mansion, vo);
        return vo;
    }
}
